package com.dly.blog.service;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dly.blog.exception.CommonExceptionEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class WeChatServiceImpl implements WeChatService {

    private String appId = "wxe9c6f069fc8c62d4";

    private String secret = "9415cf623e473054db58cefb2425a57e";


    @Override
    public String getOpenId(String code) {
        try {
            log.info("微信获取openId开始code:{}", code);
            final String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + this.appId +
                    "&secret=" + this.secret + "&js_code=" + code + "&grant_type=authorization_code";
            String response = HttpRequest.get(url).execute().body();
            log.info("微信获取openId结束:{}", response);
            final JSONObject block = JSONUtil.parseObj(response);
            final String openid = block.getStr("openid");
            assert openid != null;
            return openid;
        } catch (Exception e) {
            throw CommonExceptionEnum.WX_SEND_ERROR.getCommonException();
        }
    }

    @Override
    public String getAccessToken() {
        try {
            final String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secret;
            final String response = HttpRequest
                    .get(accessTokenUrl)
                    .execute()
                    .body();
            final JSONObject jsonObject = JSONUtil.parseObj(response);
            String token = jsonObject.getStr("token");
            assert token != null;
            return token;
        } catch (Exception e) {
            throw CommonExceptionEnum.WX_SEND_ERROR.getCommonException();
        }
    }

}